package com.frxuexi.shop.view

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup.LayoutParams
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.frxuexi.base.db.ShopLoveEntity
import com.frxuexi.base.entity.CommentBean
import com.frxuexi.base.entity.CommentBeanItem
import com.frxuexi.base.entity.ShopDetailBean
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.base.utils.BitmapUtils
import com.frxuexi.base.utils.LiveDataBus
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.CommentAdapter
import com.frxuexi.shop.databinding.ActivityShopDetailBinding
import com.frxuexi.shop.intent.ShopIntent
import com.frxuexi.shop.viewmodel.ShopViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/shop/ShopDetailActivity")
@AndroidEntryPoint
class ShopDetailActivity : BaseActivity<ActivityShopDetailBinding,ShopIntent,ShopViewModel>() {

    @Autowired
    lateinit var sid:String

    lateinit var detailBean:ShopDetailBean

    val commentAdapter by lazy { CommentAdapter() }
    var isLove=false
    override fun getVM(): ShopViewModel {
        return viewModels<ShopViewModel>().value
    }

    override fun getBind(): ActivityShopDetailBinding {
        return ActivityShopDetailBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                detailBean = it.data as ShopDetailBean
                                Glide.with(this@ShopDetailActivity).load(detailBean.productInfo.image).into(binding.shopdetailIv)
                                binding.shopdetailTitle.setText(detailBean.productInfo.storeName)
                                binding.shopdetailPrice.setText("￥${detailBean.productInfo.price}")
                            }
                            RequestType.ADD->{
//                                ToastUtils.showLong("收藏成功"+it.data)
                                binding.shopdetailLove.setImageResource(com.frxuexi.base.R.drawable.ic_action_love)
                                isLove=true
                            }
                            RequestType.ITEM->{
                                binding.shopdetailLove.setImageResource(com.frxuexi.base.R.drawable.ic_action_love)
                                isLove=true
                            }
                            RequestType.DELETE->{
                                val data = it.data as Int
                                if(data>0){
                                    binding.shopdetailLove.setImageResource(com.frxuexi.base.R.drawable.ic_action_nolove)
                                    isLove=false
                                }
                            }

                            RequestType.COMMENTS->{
                                val items = it.data as CommentBean
                                commentAdapter.apply {
                                    addData(items.list)
                                    notifyDataSetChanged()
                                }
                            }

                            RequestType.ADDCART->{
                                Log.i("lr",it.data.toString())
                                ToastUtils.showLong("添加成功")
                                LiveDataBus.with<String>("key").postValue("3")
                                finish()
                            }

                            else -> {}
                        }

                    }


                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        vm.sendIntent(ShopIntent.getShopDetail(sid.toInt()))

        val banner_imgs = listOf<String>(
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/7a6475bba07c47bb98e5db0e0d21c8ebq5sw2kijlc.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/37382cca048b4011bdbacd3cbbe0814daw1o5x0tco.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/fef1aee22a04466d93693f5791d44bfd2rsm469mcr.jpg"
        )
        binding.banner.apply {
            setImages(banner_imgs)
            setImageLoader(object :ImageLoader(){
                override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
//                    Glide.with(context!!).load(path.toString()).into(imageView!!)
                    BitmapUtils.getInstance(context!!).loadBitmap(path.toString(),LayoutParams.MATCH_PARENT,200){
                        imageView?.setImageBitmap(it)
                    }
                }
            })
            start()
        }

        binding.shopdetailLove.setOnClickListener {
            val shopLoveEntity = ShopLoveEntity(
                sid.toLong(),
                detailBean.productInfo.storeName,
                detailBean.productInfo.price,
                detailBean.productInfo.image
            )
            if(isLove){//取消
                vm.sendIntent(ShopIntent.deleteShop(shopLoveEntity))
            }else {
                vm.sendIntent(ShopIntent.insertShop(shopLoveEntity))
            }
        }

        vm.sendIntent(ShopIntent.selectShopById(sid.toLong()))

        vm.sendIntent(ShopIntent.getComments(sid.toInt(),1,0))

        binding.shopdetailCommentRv.apply {
            adapter=commentAdapter
            layoutManager=LinearLayoutManager(this@ShopDetailActivity)
        }

        binding.shopdetailLove.setOnLongClickListener {
            ArouterManager.navigation(this,"/shop/ShopLoveActivity")
            return@setOnLongClickListener true
        }

        binding.shopdetailAdd.setOnClickListener {
            vm.sendIntent(ShopIntent.addCart(mapOf("cartNum" to 1,"productAttrUnique" to detailBean.productValue.默认.id,"productId" to detailBean.productValue.默认.productId)))
        }

        binding.shopdetailTab.apply {
            addTab(newTab().setText("详情"))
            addTab(newTab().setText("评论"))
            addOnTabSelectedListener(object :OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if(tab?.position==0){
                        binding.shopdetailIv.visibility=View.VISIBLE
                        binding.shopdetailCommentRv.visibility=View.GONE
                    }else{
                        binding.shopdetailIv.visibility=View.GONE
                        binding.shopdetailCommentRv.visibility=View.VISIBLE
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })
        }
    }
}